import React, { useEffect, useState } from "react";
import {
  Button,
  Form,
  Input,
  Popconfirm,
  Table,
  Modal,
  InputNumber,
  Select,
  DatePicker,
} from "antd";
import { getUser, addUser, editUser, delUser } from "../../api";
import dayjs from "dayjs";
import "./user.css";

const User = () => {
  const [listData, setListData] = useState({
    name: "",
  });
  // 0 新增  1 编辑
  const [modalType, setModalType] = useState(0);
  // 弹窗打开状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 表格行头数据
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "年龄",
      dataIndex: "age",
    },
    {
      title: "性别",
      dataIndex: "sex",
      render: (val) => {
        return val ? "男" : "女";
      },
    },
    {
      title: "地址",
      dataIndex: "addr",
    },
    {
      title: "出生日期",
      dataIndex: "birth",
    },
    {
      title: "操作",
      dataIndex: "action",
      render: (_, record) => {
        return (
          <div className="flex-box">
            <Button
              onClick={() => handleClick("edit", record)}
              style={{ marginRight: "5px" }}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="此操作将删除该用户，是否继续？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => handleDelete(record)}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const [tableData, setTableData] = useState([]);

  const [form] = Form.useForm(); //获取表单实例

    // 删除
    const handleDelete = ({id}) => {
      delUser({id}).then(() => {
        getTableData();
      })
    };

  const handleClick = (type, record) => {
    if (type === "add") {
      setModalType(0);
      form.resetFields();
    } else {
      setModalType(1);
      if (!record) return;
      const cloneData = JSON.parse(JSON.stringify(record));
      cloneData.birth = dayjs(cloneData.birth);
      // 表单数据回填
      form.setFieldsValue(cloneData);
    }
    setIsModalOpen(!isModalOpen);
  };
  // 搜索用户
  const handleFinish = (values) => {
    console.log(values);
    setListData({
      name: values.keyword,
    });
    // getTableData();  
    // 此处是异步请求 不会立即刷新 可以采用useEffect
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    // 清空表单
    form.resetFields();
  };
  // 表单提交逻辑
  const handleOk = () => {
    console.log("表单提交", form.getFieldValue())
    form.validateFields().then((values) => {
      console.log("表单值:", values);
  
      if (modalType === 0) {
        // 新增逻辑
        addUser(values).then(() => {
          getTableData(); // 刷新列表
          handleCancel();
        });
      } else {
        // 编辑逻辑
        editUser(values).then(() => {
          getTableData(); // 刷新列表
          handleCancel();
        });
      }
    }).catch((error) => {
      console.log("表单验证失败:", error);
    });
  };

  const getTableData = () => {
    getUser(listData).then(({ data }) => {
      setTableData(data.list);
    });
  };
  // 搜索后刷新列表
  useEffect(() => {
    getTableData();
  }, [listData]);
  return (
    <div className="user">
      <div className="flex-box space-between">
        <Button type="primary" onClick={() => handleClick("add")}>
          新增
        </Button>
        <Form layout="inline" onFinish={handleFinish}>
          <Form.Item name="keyword">
            <Input placeholder="请输入关键字" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table style={{ marginTop: "10px" }} columns={columns} dataSource={tableData} rowKey={"id"}></Table>
      <Modal
        open={isModalOpen}
        title={modalType === 0 ? "新增用户" : "编辑用户"}
        onCancel={handleCancel}
        onOk={handleOk}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          labelAlign="left"
        >
          {/* 获取ID  但不需要可见 */}
          {modalType === 1 && <Form.Item name="id" hidden />}
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[
              { required: true, message: "请输入年龄" },
              {
                type: "number",
                min: 0,
                max: 120,
                message: "年龄在0-120之间",
              },
            ]}
          >
            <InputNumber placeholder="请输入年龄" />
          </Form.Item>
          <Form.Item
            label="性别"
            name="sex"
            rules={[{ required: true, message: "请选择性别" }]}
          >
            <Select
              placeholder="请选择性别"
              options={[
                {
                  value: 0,
                  label: "女",
                },
                {
                  value: 1,
                  label: "男",
                },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="出生日期"
            name="birth"
            rules={[{ required: true, message: "请选择出生日期" }]}
          >
            <DatePicker placeholder="请选择出生日期" format={"YYYY-MM-DD"} />
          </Form.Item>
          <Form.Item
            label="地址"
            name="addr"
            rules={[{ required: true, message: "请输入地址" }]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default User;
